package com.jzg.mvc.api.cabinet;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jzg.common.controller.BaseController;
import com.jzg.common.entity.Box;
import com.jzg.common.entity.Module;
import com.jzg.common.model.biz.Cab;
import com.jzg.common.model.biz.CabConfig;
import com.jzg.common.model.biz.CabModule;
import com.jzg.common.model.biz.CabModuleBoard;
import com.jzg.common.model.biz.CabModuleFaultBox;
import com.jzg.common.model.biz.CabPicture;
import com.jzg.common.model.biz.CabStore;
import com.jzg.common.model.biz.CabStoreBox;
import com.jzg.common.model.biz.CabStoreLog;
import com.jzg.common.model.biz.CabUser;
import com.jzg.common.model.sys.SysOrg;
import com.jzg.common.model.sys.SysUser;
import com.jzg.common.render.RenderBean;
import com.jzg.common.render.RenderLayuiBean;
import com.jzg.common.util.S3Util;
import com.jzg.common.util.UuidUtil;
import com.jzg.common.util.YTUtil;
import com.jzg.mvc.api.cabinet.service.CabService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Path(value = "/api/cab", viewPath = "")
public class CabController extends BaseController{

	@Inject
	private CabService srv;
	
	/**
	 * 人脸验证
	 */
	public void verifyFace() {
		String auth=this.getPara("auth");
		String face=this.getPara("face");
		List<SysUser> cabUsers=SysUser.dao.find("select a.* from "+SysUser.TABLE_NAME+" a,"+CabUser.TABLE_NAME+" b where a.id=b.userId and b.cabId=? ",auth);
		for(SysUser sysUser:cabUsers) {
			if(!StrKit.isBlank(sysUser.getPHOTO())) {
				RenderBean renderBean=YTUtil.httpURLConnectionPOSTForSL(face, sysUser.getPHOTO());
				if(renderBean.getCode()==200) {
					renderSuccess("成功", sysUser.getID());
					return;
				}
			}
		}
		renderError("失败！");
	}
	
	public void save () {
		Cab cab = getModel(Cab.class);
		
		if(cab==null) {
			renderError("参数不完整！");
			return;
		}
		
		SysOrg sysOrg = SysOrg.dao.findById(cab.getOrgId());
		if(sysOrg==null) {
			renderError("部门不存在，请刷新重试！");
			return;
		}
		
		String license;
		if(!StrKit.isBlank(sysOrg.getCODE())) {
			license = "PL-JZG-"+sysOrg.getCODE()+"-"+(int)((Math.random()*9+1)*1000);
		}else {
			license = "PL-JZG-"+"-"+(int)((Math.random()*9+1)*1000);
		}
		
		if (StrKit.notBlank(cab.getId())) {
			if (cab.update()) {
				renderSuccess("更新成功！");
			} else {
				renderError("更新失败！");
			}
		} else {
			cab.setId(license);
			cab.setLicense(license);
			cab.setName(sysOrg.getNAME());
			if (cab.save()) {
				renderSuccess("保存成功！");
			} else {
				renderError("保存失败！");
			}
		}
		
	}
	
	@Before(Tx.class)
	public void saveModule() {
		String rows=this.getPara("rows");
		if(StrKit.isBlank(rows)) {
			this.renderError("柜子信息为空！");
			return;
		}
		try {
			JSONArray array=JSONArray.fromObject(rows);
			for(Object object:array) {
				JSONObject row=JSONObject.fromObject(object);
				if(row!=null) {
					CabStoreLog cabStoreLog=new CabStoreLog();
					cabStoreLog.setId(row.getString("id"));
					cabStoreLog.setCabId(row.getString("cabinetId"));
					cabStoreLog.setStoreId(row.getString("storeId"));
					cabStoreLog.setStatus(row.getString("status"));
					cabStoreLog.setCreateUserId(row.getString("userId"));
					cabStoreLog.setCreateTime(new Date(System.currentTimeMillis()));
					cabStoreLog.setRecordTime(row.getString("createTime"));
						if(!cabStoreLog.save()) {
							throw new Exception("保存日志异常！");
						}
				}
			}
			this.renderSuccess("日志保存成功！");
		}catch (Exception e) {
			this.renderError("日志信息空！");
		}
	}
	
	public void listData() {
		RenderLayuiBean renderBean = srv.listData(this);
		this.renderJson(renderBean);
	}
	
	public void cabBoxInfo() {
		String cabId = getPara("cabId");
		String caseNo  = getPara("caseNo");
		
		if(StrKit.isBlank(cabId)) {
			renderError("参数必填！");
			return;
		}
		
		List<Module> res = new ArrayList<Module>();
		
		List<CabModule> cabModules = CabModule.dao.find("select * from "+CabModule.TABLE_NAME+" where cabId=? order by sort asc ",cabId);
		for (CabModule cabModule : cabModules) {
			
			SysOrg sysOrg = SysOrg.dao.findFirst("SELECT * FROM "+SysOrg.TABLE_NAME+" WHERE ID IN (SELECT ORGID FROM "+Cab.TABLE_NAME+" WHERE ID=? ) ",cabId);
			Module module = new Module();
			module.setCabId(cabModule.getCabId());
			module.setCaseNo(caseNo);
			module.setType(cabModule.getType());
			module.setName(sysOrg==null?cabModule.getName():sysOrg.getNAME()+"-"+cabModule.getName());
			module.setCode(cabModule.getCode());
			
			int usedNum = Db.queryInt("select count(*) from "+CabStoreBox.TABLE_NAME+" where moduleId=?",cabModule.getId());
			int faultNum = Db.queryInt("select count(*) from "+CabModuleFaultBox.TABLE_NAME+" where status='0' and moduleId=? ",cabModule.getId());
			
			module.setUsedNum(usedNum);
			module.setErrorNum(faultNum);
			module.setFreeNum(cabModule.getTotal()-usedNum-faultNum);
			module.setTotal(cabModule.getTotal());
			
			List<CabModuleBoard> boards = CabModuleBoard.dao.find("select * from "+CabModuleBoard.TABLE_NAME+" where moduleId=? order by serialNo  ",cabModule.getId());
			cabModule.setBoards(boards);

			List<Box> boxs = new ArrayList<Box>();
			
			if(boards!=null && boards.size()>0) {
				int boxNo=0;
				for(int r=1;r<=5;r++) {
					for(CabModuleBoard board : boards) {
						for(int i=0;i<board.getTotal();i++) {
							boxNo++;
							int xh = boxNo;
							int serialNo = r+i*5;
							Box box = new Box();
							box.setBoardId(board.getId());
							box.setBoardNo(board.getSerialNo());
							box.setSortNo(xh);
							box.setSerialNo(serialNo);
							box.setBoxStatus("0");
							boxs.add(box);
							//System.out.println(cabModule.getName()+">>>板号"+board.getSerialNo()+">>>板子序号"+serialNo+">>>序号"+xh);
							if((i+1)*5>=board.getTotal()) {
								break;
							}
						}
					}
				}
			}
			
			srv.boxStatus(boxs,caseNo);
			if(StrKit.notBlank(caseNo)) {
				srv.boxCaseStatus(boxs,caseNo);
			}
			module.setBoxs(boxs);
			res.add(module);
		}
		renderSuccess("查询成功！",res);
		
	}
	
	/**
	 * 0-正常1-报捕2-报诉99-超时
	 */
	public void getCabCaseStatus() {
		String cabId = getPara("cabId");
		
		if(StrKit.isBlank(cabId)) {
			renderError("参数必填！");
			return;
		}
		
		SysOrg sysOrg = SysOrg.dao.findFirst("SELECT * FROM "+SysOrg.TABLE_NAME+" WHERE ID IN (SELECT ORGID FROM "+Cab.TABLE_NAME+" WHERE ID=? ) ",cabId);
		if(sysOrg==null) {
			renderError("部门不存在，请刷新重试！");
			return;
		}
		
		int caseNum=0;//总数
		int normalNum=0;//正常2
		int overdueNum=0;//超期-1
		int warnNum=0;//预警0
		int trialNum=0;//待审1
		int completeNum=0;//完成3
		List<CabStore>  stores = CabStore.dao.find("select * from "+CabStore.TABLE_NAME+" where cabId=? ",cabId);
		if(stores!=null && stores.size()>0) {
			caseNum = stores.size();
			for (CabStore cabStore : stores) {
				if(StrKit.equals("-1", cabStore.getStatus())) {
					overdueNum ++;
				}else if(StrKit.equals("0", cabStore.getStatus())) {
					warnNum ++;
				}else if(StrKit.equals("1", cabStore.getStatus())) {
					trialNum ++;
				}else if(StrKit.equals("2", cabStore.getStatus())) {
					normalNum ++;
				}else if(StrKit.equals("3", cabStore.getStatus())){
					completeNum ++;
				}else {
					if(StrKit.equals("53010305", sysOrg.getCODE())) {
						trialNum ++;
					}else {
						normalNum ++;
					}
				}
			}
		}
		
		Map<String, Integer> res = new HashMap<String, Integer>();
		if(StrKit.equals("53010305", sysOrg.getCODE())) {
			res.put("caseNum",caseNum);
			res.put("overdueNum", overdueNum);
			res.put("warnNum", warnNum);
			res.put("trialNum", trialNum);
			res.put("completeNum", completeNum);
		}else {
			res.put("caseNum",caseNum);
			res.put("overdueNum", overdueNum);
			res.put("warnNum", warnNum);
			res.put("normalNum", normalNum);
		}
		renderSuccess("查询成功！", res);
	}
	
	public void saveConfig () {
		CabConfig cabConfig = getModel(CabConfig.class);
		if(cabConfig==null) {
			renderError("参数不完整！");
			return;
		}
		if (StrKit.notBlank(cabConfig.getId())) {
			if (cabConfig.update()) {
				renderSuccess("更新成功！");
			} else {
				renderError("更新失败！");
			}
		} else {
			Db.use().delete("delete from "+CabConfig.TABLE_NAME);
			cabConfig.setId(UuidUtil.getUUID());
			if (cabConfig.save()) {
				renderSuccess("保存成功！");
			} else {
				renderError("保存失败！");
			}
		}
	}
	
	
	/*********************************************************客户端同步**************************************************************/
	
	/**
	 * 保存柜子组信息
	 */
	@Before(Tx.class)
	public void saveModules() {
		String cabinetId=this.getPara("cabinetId");
		String rows=this.getPara("rows");
		if(StrKit.isBlank(rows)) {
			this.renderError("柜子板块信息空！");
			return;
		}
		try {
			JSONArray array=JSONArray.fromObject(rows);
			if(array!=null && array.size()>0) {
				StringBuffer sb=new StringBuffer();
				for(Object object:array) {
					JSONObject row=JSONObject.fromObject(object);
					if(row!=null) {
						CabModule cabModule=CabModule.dao.findById(row.getString("id"));
						if(cabModule==null) {
							cabModule=new CabModule();
							cabModule.setId(row.getString("id"));
							cabModule.setCabId(cabinetId);
							cabModule.setName(row.getString("name"));
							cabModule.setCode(row.getString("code"));
							cabModule.setComPort(row.getInt("comPort"));
							cabModule.setBaudRate(row.getInt("baudRate"));
							cabModule.setTotal(row.getInt("total"));
							cabModule.setSort(row.getInt("sort"));
							cabModule.setType(row.getString("type"));
							if(!cabModule.save()) {
								throw new Exception("保存柜子板块异常");
							}
						}else {
							boolean isUpdate = false;
							if(!StrKit.equals(cabModule.getName(), row.getString("name"))) {
								cabModule.setName(row.getString("name"));
								isUpdate = true;
							}
							if(!StrKit.equals(cabModule.getCode(), row.getString("code"))) {
								cabModule.setName(row.getString("code"));
								isUpdate = true;
							}
							if(!StrKit.equals(cabModule.getComPort().toString(), row.getString("comPort"))) {
								cabModule.setComPort(row.getInt("comPort"));
								isUpdate = true;
							}
							if(!StrKit.equals(cabModule.getBaudRate().toString(), row.getString("baudRate"))) {
								cabModule.setBaudRate(row.getInt("baudRate"));
								isUpdate = true;
							}
							if(!StrKit.equals(cabModule.getTotal().toString(), row.getString("total"))) {
								cabModule.setTotal(row.getInt("total"));
								isUpdate = true;
							}
							if(!StrKit.equals(cabModule.getSort().toString(), row.getString("sort"))) {
								cabModule.setSort(row.getInt("sort"));
								isUpdate = true;
							}
							
							if(!StrKit.equals(cabModule.getType().toString(), row.getString("type"))) {
								cabModule.setType(row.getString("type"));
								isUpdate = true;
							}
							
							if(isUpdate) {
								cabModule.update();
							}
						}
						sb.append("'").append(cabModule.getId()).append("'").append(",");
					}
				}
				if(!StrKit.isBlank(sb.toString())) {
					Db.delete("delete from "+CabModule.TABLE_NAME+" where cabId=? and  id not in ("+(sb.substring(0,sb.length()-1))+") ",cabinetId);
				}
				this.renderSuccess("柜子板块保存成功！");
			}else {
				this.renderError("柜子板块信息空！");
			}
		}catch (Exception e) {
			this.renderError("柜子板块信息空！");
		}
	}
	
	/**
	 * 柜子板块信息
	 */
	@Before(Tx.class)
	public void saveBoards() {
		String cabinetId=this.getPara("cabinetId");
		String rows=this.getPara("rows");
		if(StrKit.isBlank(rows)) {
			this.renderError("柜子板块信息空！");
			return;
		}
		try {
			JSONArray array=JSONArray.fromObject(rows);
			if(array!=null && array.size()>0) {
				StringBuffer sb=new StringBuffer();
				for(Object object:array) {
					JSONObject row=JSONObject.fromObject(object);
					if(row!=null) {
						CabModuleBoard cabModuleBoard=CabModuleBoard.dao.findById(row.getString("id"));
						if(cabModuleBoard==null) {
							cabModuleBoard=new CabModuleBoard();
							cabModuleBoard.setId(row.getString("id"));
							cabModuleBoard.setCabId(cabinetId);
							cabModuleBoard.setModuleId(row.getString("cabinetId"));
							cabModuleBoard.setSerialNo(row.getInt("boardNo"));
							cabModuleBoard.setTotal(row.getInt("boxTotal"));
							if(!cabModuleBoard.save()) {
								throw new Exception("保存柜子板块异常");
							}
						}else {
							boolean isUpdate = false;
							if(!StrKit.equals(cabModuleBoard.getSerialNo().toString(), row.getString("boardNo"))) {
								cabModuleBoard.setSerialNo(row.getInt("boardNo"));
								isUpdate = true;
							}
							if(!StrKit.equals(cabModuleBoard.getTotal().toString(), row.getString("boxTotal"))) {
								cabModuleBoard.setTotal(row.getInt("boxTotal"));
								isUpdate = true;
							}
							if(isUpdate) {
								cabModuleBoard.update();
							}
						}
						
						sb.append("'").append(cabModuleBoard.getId()).append("'").append(",");
					}
				}
				if(!StrKit.isBlank(sb.toString())) {
					Db.delete("delete from "+CabModuleBoard.TABLE_NAME+" where cabId=? and  id not in ("+(sb.substring(0,sb.length()-1))+") ",cabinetId);
				}
				this.renderSuccess("柜子板块保存成功！");
			}else {
				this.renderError("柜子板块信息空！");
			}
		}catch (Exception e) {
			this.renderError("柜子板块信息空！");
		}
	}
	
	/**
	 * 获取配置
	 */
	public void getConfig() {
//		String cabinetId=this.getPara("cabinetId");
//		if(StrKit.isBlank(cabinetId)) {
//			this.renderError("授权信息空！");
//			return;
//		}
		CabConfig cabConfig=CabConfig.dao.findFirst("select id,name,phone,copyright,isBiopsy from "+CabConfig.TABLE_NAME+" LIMIT 1 ");
		this.renderSuccess("成功！",cabConfig);
//		if(cabConfig!=null) {
//			System.out.println(JsonKit.toJson(cabConfig));
//			this.renderSuccess("成功！",cabConfig);
//			return;
//		}
		//this.renderError("无效授权！");
	}
	
	
	
	/**
	 * 故障
	 */
	public void getFault() {
		String cabinetId = getPara("cabinetId");
		List<CabModuleFaultBox> cabModuleFaultBoxs=CabModuleFaultBox.dao.find("select * from "+CabModuleFaultBox.TABLE_NAME+" where status='0' and cabId=? ",cabinetId);
		this.renderSuccess("成功!", cabModuleFaultBoxs);
	}
	
	public void getUsers() {
		String cabinetId = getPara("cabinetId");
		int pageNumber= this.getParaToInt("pageNumber",1);
		
		if(StrKit.isBlank(cabinetId)) {
			renderError("柜子授权为空！");
			return;
		}
		
		Cab cab = Cab.dao.findById(cabinetId);
		if(cab==null) {
			renderError("柜子授权错误！");
			return;
		}
		
		Page<SysUser>  pages=SysUser.dao.paginate(pageNumber, 10, "select a.*,b.roleName,b.roleKey  "," from "+SysUser.TABLE_NAME+" a,"+CabUser.TABLE_NAME+" b where a.id=b.userId and b.cabId=? ",cabinetId);
		if(pages!=null && pages.getPageSize()>0) {
			this.renderSuccess("成功!", pages.getList());
			return;
		}
		
//		if(StrKit.equals("PL-JZG-53010305-2224", cabinetId)) {//法制大队
//			Page<SysUser>  pages=SysUser.dao.paginate(pageNumber, 10, "select a.*,b.roleName,b.roleKey  "," from "+SysUser.TABLE_NAME+" a,"+CabUser.TABLE_NAME+" b where a.id=b.userId and b.cabId=? ",cabinetId);
//			if(pages!=null && pages.getPageSize()>0) {
//				this.renderSuccess("成功!", pages.getList());
//				return;
//			}
//		}else {//其他派出所
//			Page<SysUser>  pages=SysUser.dao.paginate(pageNumber, 10, "select a.*,b.roleName,b.roleKey  "," from "+SysUser.TABLE_NAME+" a,"
//					+CabUser.TABLE_NAME+" b where a.id=b.userId and b.cabId=? and a.ID IN (SELECT USERID FROM SYS_USER_ORG WHERE ORGID='"+cab.getOrgId()+"') ",cabinetId);
//			if(pages!=null && pages.getPageSize()>0) {
//				this.renderSuccess("成功!", pages.getList());
//				return;
//			}
//		}
	}
	
	public void saveFpr() {
		String rows = this.getPara("rows");
		if (StrKit.isBlank(rows)) {
			this.renderError("用户信息空！");
			return;
		}
		try {
			JSONArray array = JSONArray.fromObject(rows);
			if (array != null && array.size() > 0) {
				for (Object object : array) {
					JSONObject row = JSONObject.fromObject(object);
					if (row != null) {
						
						SysUser sysUser = SysUser.dao.findById(row.getString("id"));
						if(sysUser!=null) {
							if(StrKit.notBlank(row.getString("fpr1")) && !StrKit.equals("null",row.getString("fpr1")) 
									&& !StrKit.equals("\"null\"",row.getString("fpr1"))) {
								sysUser.setFpr1(row.getString("fpr1"));
							}
							if(StrKit.notBlank(row.getString("fpr2")) && !StrKit.equals("null",row.getString("fpr2")) 
									&& !StrKit.equals("\"null\"",row.getString("fpr2"))) {
								sysUser.setFpr2(row.getString("fpr2"));
							}
							if(!sysUser.update()) {
								throw new Exception("更新用户异常！");
							}
						}
					}
				}
				this.renderSuccess("用户更新成功！");
			}else {
				this.renderError("用户信息为空！");
			}
		} catch (Exception e) {
			this.renderError("用户信息为空！");
		}
	}
	
	public void getPictures() {
		//String cabinetId = getPara("cabinetId");
		List<CabPicture> cabPictures=CabPicture.dao.findAll();
		if(cabPictures!=null && cabPictures.size()>0) {
			this.renderSuccess("成功!", cabPictures);
			return;
		}
		this.renderError("失败！");
	}
	
	public void downPicture() {
		String pictureId = getPara("pictureId");
		CabPicture cabPicture=CabPicture.dao.findById(pictureId);
		if(cabPicture!=null) {
			File file=new File(PathKit.getWebRootPath() + cabPicture.getUrl());
			if(file.exists()) {
				renderFile(file);
				return;
			}
			this.renderNull();
		}else {
			this.renderNull();
		}
	}
	
	public void getS3List() {
		String cabId = getPara("cabId");
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		renderSuccess("成功！", S3Util.listObject(cabId+"/",startDate,endDate));
	}
	
	public void getS3Vieo() {
		String key = getPara("key");
		renderSuccess("成功！", S3Util.getVideo(key));
	}
	
	public static void main(String[] args) {
		System.out.println((int)((Math.random()*9+1)*1000));
	}

}
